package com.qfjy.project.weixin.api.tuling;

import com.qfjy.project.weixin.api.tuling.bean.InputTextBean;
import com.qfjy.project.weixin.api.tuling.bean.Perception;
import com.qfjy.project.weixin.api.tuling.bean.TuLingBean;
import com.qfjy.project.weixin.api.tuling.bean.UserInfoBean;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
@Slf4j
public class TuLingUtil {

    @Resource
    private RestTemplate restTemplate;

    private static String TULING_API_POST_URL = "http://openapi.turingapi.com/openapi/api/v2";

    /**
     * 封装请求入参
     * @param text
     * @param apiKey
     * @return
     */
    public JSONObject requestJSONObject(String text,String apiKey){
        TuLingBean tuLingBean = new TuLingBean();
        tuLingBean.setReqType(0);

        Perception perception = new Perception();
        InputTextBean inputText = new InputTextBean();
        inputText.setText(text);
        perception.setInputText(inputText);

        tuLingBean.setPerception(perception);

        UserInfoBean userInfo = new UserInfoBean();
        userInfo.setApiKey(apiKey);
        userInfo.setUserId("java2303");
        tuLingBean.setUserInfo(userInfo);

        JSONObject jsonObject = JSONObject.fromObject(tuLingBean);
        log.info(jsonObject.toString());
        return jsonObject;

    }

    public String responseResult(JSONObject jsonObject){
        String result = restTemplate.postForObject(TULING_API_POST_URL,jsonObject, String.class);

        JSONObject jsonObject1 = JSONObject.fromObject(result);

        JSONArray jsonArray = (JSONArray) jsonObject1.get("results");

        JSONObject jsonObject2 = (JSONObject) jsonArray.get(0);

        JSONObject jsonObject3 = (JSONObject) jsonObject2.get("values");
        String resultMsg = jsonObject3.getString("text");
        log.info(resultMsg);
        return resultMsg;
    }


    /**
     * 根据输入的内容文本 得到 智能聊天的第三方接口返回
     * @param text
     * @return
     */
    public String sendMessage(String text){
        JSONObject jsonObject = this.requestJSONObject(text, "a2248ded1f8842729a36589d1829a986");
        String result = this.responseResult(jsonObject);
        return result;
    }
}
